import axios from 'axios';
import { Toast } from 'vant';
import { getToken, setToken } from '@/utils/auth';
import qs from 'qs';
import BASE_URL from '../config/api';

const uploadUrl = [
];

// 创建axios实例
const service = axios.create({
  baseURL: BASE_URL + '/DataServices', // api 的 base_url
  timeout: 15000, // 请求超时时间
  headers: {
    // 'Content-Type': 'application/json'
  },
  withCredentials: true,
  transformRequest: [function (data) {
    if (!(data instanceof FormData)) {
      data = qs.stringify(data)
    }
    return data;
  }],
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    if (config.params && typeof config.params.page !== 'undefined' && typeof config.params.pagesize === 'undefined') {
      config.params.pageSize = 10;
    }
    // if (!config.params || typeof config.params.pageNum === 'undefined') {
    //   Toast.loading({
    //     duration: 0,
    //     forbidClick: true,
    //     message: '加载中'
    //   });
    // }
    const token = getToken();
    if (token) config.headers['cloud_builder_access_token'] = token;
    if (uploadUrl.filter(url => config.url.includes(url)).length > 0) {
      config.headers['Content-Type'] = 'multipart/form-data';
    }
    return config;
  },
  (error) => {
    // Do something with request error
    Promise.reject(error);
  },
);

// response 拦截器
service.interceptors.response.use(
  (response) => {
    /**
     * code为非000000是抛错
     */
    const res = response.data;
    const token = response.headers['auth-token'];
    if (token) setToken(token);
    if (res.ok !== 1) {
      return Promise.reject(res);
    }
    return res;
  },
  error => {
    if (error.toString().includes('Network Error')) {
      Toast('网络错误，请稍后再试');
    } else if (error.toString().includes('timeout')) {
      Toast('当前网络状况较差，请稍候再试');
    }
    return Promise.reject(error);
  },
);
export default service;
